package com.java2007.hotel.controller.backend;

import com.alibaba.druid.util.StringUtils;
import com.java2007.hotel.constant.ServletConstant;
import com.java2007.hotel.controller.Controller;
import com.java2007.hotel.pojo.Food;
import com.java2007.hotel.pojo.FoodType;
import com.java2007.hotel.service.FoodService;
import com.java2007.hotel.service.FoodTypeService;
import com.java2007.hotel.service.impl.FoodServiceImpl;
import com.java2007.hotel.service.impl.FoodtypeServiceImpl;
import com.java2007.hotel.utils.FileUtils;
import com.java2007.hotel.utils.UuidUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author Reckeys
 * @version V1.0
 * @date 2021/01/23
 **/
@WebServlet("/food")
@MultipartConfig
public class FoodController extends Controller {
    private FoodService foodService = new FoodServiceImpl();
    private FoodTypeService foodTypeService = new FoodtypeServiceImpl();

    /**
     * 通过foodName查询，值为null则查询所有
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     * @throws SQLException
     */
    public String findByFoodName(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取输入的值
        String foodName = request.getParameter("keyword");
        //查询typeName
        List<Food> foodList = foodService.findByFoodName(foodName);
        request.setAttribute("foodList", foodList);
        request.setAttribute("foodName", foodName);
        return "forward:/backend/detail/food/food-list.jsp";
    }

    /**
     * 根据foodId删除
     *
     * @param request
     * @param response
     * @return 删除成功
     * @throws ServletException
     * @throws IOException
     * @throws SQLException
     */
    public String deleteByTypeId(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取输入的值
        String foodIdStr = request.getParameter("foodId");
        Integer foodId = Integer.valueOf(foodIdStr);
        foodService.deleteByFoodId(foodId);
        return "redirect:/food?method=findByFoodName&keyword= ";
    }

    /**
     * 通过id查询food信息，并回显
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     * @throws SQLException
     */
    public String findByFoodId(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取输入的值
        String foodIdStr = request.getParameter("foodId");
        Integer foodId = Integer.valueOf(foodIdStr);
        //菜和菜类别的所有信息
        Food food = foodService.findByfoodId(foodId);
        List<FoodType> foodType = foodTypeService.findByTypeName("");

        request.setAttribute("food", food);
        request.setAttribute("foodType", foodType);
        return "forward:/backend/detail/food/food-update.jsp";
    }

    /**
     * 修改food
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     * @throws SQLException
     * @throws IllegalAccessException
     */
    public String updateFood(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //封装参数，执行保存业务
        Map<String, String[]> parameterMap = request.getParameterMap();
        Food food = new Food();
        BeanUtils.populate(food, parameterMap);
        /*将原先的地址先封装进food实例中，
        如果有文件上传，将新的地址封装进food实例中
        */

//        //判断重名
//        int i = 0;
//        List<Food> byFoodName = foodService.findByFoodName(food.getFoodName().trim());
//        for (Food food1 : byFoodName) {
//            if (food1.getFoodName().trim().equals(food.getFoodName().trim())){
//                i = i +1;
//            }
//        }
//        if (i >= 2){
//            return "名字重复";
//        }

        //新的文件上传
        String fileName = FileUtils.fileUpload(request);
        if (fileName != null && !fileName.isEmpty()){
            food.setFoodImage("file/" + fileName);
        }

        //Part part = request.getPart("imageUrl");
        ////判断文件是否上传，如果上传：上传文件修改文件地址   如果没上传：不修改地址
        //String filename = part.getSubmittedFileName();
        //if (!"".equals(filename)) {
        //    //获取文件后缀
        //    String suffix = filename.substring(filename.lastIndexOf("."));
        //    //获取文件真实路径
        //    String imagePath = request.getSession().getServletContext().getRealPath("/file/");
        //    //将文件名修改成uuid
        //    String fileName = UuidUtils.getUuidFileName(suffix);
        //    File file = new File(imagePath + fileName);
        //    //File file = new File(imagePath, fileName);
        //    if (!file.getParentFile().exists()) {
        //        file.getParentFile().mkdirs();
        //    }
        //    //将文件写入
        //    part.write(file.getPath());
        //    //修改文件地址
        //    //food.setFoodImage(file.getPath());
        //    food.setFoodImage("file/" + fileName);
        //}

        /**
         * 创建修改时间
         */
        Date date = new Date();
        food.setFoodUpdateTime(date);
        foodService.updateFood(food);
        return "redirect:/food?method=findByFoodName&keyword= ";
    }

    /**
     * 添加菜,上传图片
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String addFood(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //封装参数，执行保存业务
        Map<String, String[]> parameterMap = request.getParameterMap();
        Food food = new Food();
        BeanUtils.populate(food, parameterMap);

//        //判断是否重名
//        List<Food> byFoodName = foodService.findByFoodName(food.getFoodName().trim());
//        for (Food food1 : byFoodName) {
//            if (food.getFoodName().trim().equals(food.getFoodName().trim())){
//                return ServletConstant.jump("名字重复", "backend/detail/food/food-save.jsp");
//            }
//        }


        //文件上传
        String fileName = FileUtils.fileUpload(request);
        if (fileName != null && !fileName.isEmpty()) {
            food.setFoodImage("file/" + fileName);
        }

        ////文件上传
        //Part part = request.getPart("imageUrl");
        //String filename = part.getSubmittedFileName();
        //if(!"".equals(filename)) {
        //    //获取文件后缀
        //    String suffix = filename.substring(filename.lastIndexOf("."));
        //    //获取文件真实路径
        //    String imagePath = request.getSession().getServletContext().getRealPath("/file/");
        //    //将文件名修改成uuid
        //    String fileName = UuidUtils.getUuidFileName(suffix);
        //    File file = new File(imagePath + fileName);
        //    //File file = new File(imagePath, fileName);
        //    if (!file.getParentFile().exists()) {
        //        file.getParentFile().mkdirs();
        //    }
        //    //将文件写入
        //    part.write(file.getPath());
        //    //封装foodImage
        //    food.setFoodImage("file/" + fileName);
        //    //food.setFoodImage(file.getPath());
        //}

        //封装创建时间
        Date date = new Date();
        food.setFoodCreateTime(date);
        foodService.addFood(food);

        return "redirect:/food?method=findByFoodName&keyword= ";
    }

    /**
     * 修改或添加菜时，回显菜类别的信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String findByTypeinf(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //查询foodType
        List<FoodType> foodTypeList = foodTypeService.findByTypeName("");
        request.setAttribute("foodTypeList", foodTypeList);
        return "forward:backend/detail/food/food-save.jsp";
    }


    /**
     * 根据foodId删除
     *
     * @param request
     * @param response
     * @return 删除成功
     * @throws ServletException
     * @throws IOException
     * @throws SQLException
     */
    public String deleteByFoodId(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取输入的值
        String foodIdStr = request.getParameter("foodId");
        Integer foodId = Integer.valueOf(foodIdStr);
        foodService.deleteByFoodId(foodId);
        return "redirect:/food?method=findByFoodName&keyword= ";
    }

    public String findFood(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取输入的值
        String foodName = request.getParameter("foodName").trim();
        String foodIdStr = request.getParameter("foodId").trim();
        //查询typeName
        Food food = foodService.findFood(foodName);
        //判断是否存在同名菜
        if (food == null){
            //不存在
            return "success";
        }
        //判断菜id是否为空
        if (foodIdStr != null || StringUtils.isEmpty(foodIdStr)){
            Integer foodId = Integer.valueOf(foodIdStr);
            if (food.getFoodId().intValue() == foodId.intValue()){
                return "success";
            }
        }
        //存在
        return "false";
    }

}